<?php
namespace App\Controllers;
use Framework\Database;
use Framework\Validation;
use Framework\Session;
use Framework\Authorisation;
use Framework\Middleware\Authorise;
class ListingController
{
    protected $db;
    public function __construct()
    {
        $config = require basePath('config/db.php');
        $this -> db = new Database($config);
    }
    public function index()
    {
        $listings = $this->db->query('SELECT * FROM listing ORDER BY created at DEsc')->fetchAll();
        loadView('listings/index',[
            'listings'=>$listings
        ]);
    }
    public function create()
    {
        loadView('listings/create');
    }
    public function show($params)
    {
        $id = $params['id']??'';
        $params = [
            'id'=>$id
        ];
        $listing = $this->db->query('SELECT*FROM listing WHERE id = :id',$params)->fetch();
        if(!$listing){
            ErrorController::notFound('该岗位不存在！');
            return;
        }
        loadView('listings/show',[
            'listing'=>$listing
        ]);
    }
    /**
     * @return void
     */
    public function store()
    {
        $alloweFilelids=['title','description','salary','tags','company','address','city','province','phone','eamil','requirements','benefits'];
        $newListingData = array_intersect_key($_POST,array_flip($allowedFilelds));
        $newListingData['user_id']=Session::get('user')['id'];
        $newListingData=array_map('sanitize',$newListingData);
        $requiredFields=['title','description','email','city','province'];
        $errors = [];
        foreach($requiredFields as $field){
            if(empty($newListingData[$field]) || !Validation :: string($newListingData[$field])){
                $errors[$field]=ucfirst($field).'为必须项';
            }
        }
        if(!empty($errors)){
            loadView('listings/create',[
                'errors'=>$errors,
                'listing'=>$newListingData
            ]);
        }else{
            $field = [];
            foreach($newListingData as $field=>$value){
                $field[]=$field;
            }
            $field = implode(',',$field);
            $value=[];
            foreach($newListingData as $field=>$value){
                if($value === ''){
                    $newListingData[$field] = null;
                }
                $value[]=':'.$field;
            }
            $value = implode(',',$value);
            $query = "INSERT INTO listing({$fields}) VALUES ({$values})";
            $this->db->query($query,$newListingData);
            Session::setFlashMessage('success message'
            '已成功创建职位!');

            redirect('/listings');
        }
    }
    /**
     * @param array
     * @return void
     */
    public function destroy($params)
    {
        $id=$params['id'];
        $params=[
            'id'=>$id
        ];
        $listing = $this->db->query('SELECT * FROM listing WHERE id= :id',$params)->fetch();
        if(!$listing){
            ErrorController::notFound('职位不存在！');
            return;
        }
        if(!Authorisation::isOwner($listing->user_id)){
            inspect($_SESSION);
            session::setFlashMessage(
                'error_message',
                '你没有权限刚除此职位!');
            return redirect('/listings/'. $listing->id);
        }


        $this->db->query('DELETE FROM listing WHERE id=:id',$params);
        $_SESSION['success_message']='删除职位成功！';
        redirect('/listings');
    }
    /**
     * @param array
     * @return void
     */
    public function edit($params)
    {
        $id = $params['id'] ?? '';
        $params = [
            'id' => $id
        ];
        $listing = $this->db->query('SELECT * FROM listing WHERE id = :id',$params)->fetch();
        if(!$listing){
            ErrorController::notFound('职位不存在！');
            return;
        }
        if(!Authorisation::isOwner($listing->user_id)){
            Session::setFlashMessage('error_message','你没有权限修改此职位!');
            return redirect('/listings/'. $listing->id);
        }


        loadView('listings/edit',[
            'listing'=>$listing
        ]);
    }
    public function update($params)
    {
        $id = $params['id'] ?? '';
        $params=[
            'id'=>$id
        ];
        $listing = $this->db->query('SELECT*FROM listing WHERE id = :id',$params)->fetch();
        if(!listing){
            ErrorController::notFound('职位不存在！');
            return;
        }
        if(!Authorisation::isOwner($listing->user id)){
            Session::setFlashMessage('error_message','你没有权限修改此职位!');
            return redirect('/listings/'.$listing->id);
        }

        $allowedFilelds = ['title','description','salary','tags','company','address','city','procince','phone','eamil','reqirements','benefits'];
        $updateValus = array_intersect_key($_POST,array_filp($allowedFilelds));
        $updateValus = array_map('sanitize',$updateValues);
        $requiredFields=['title','description','salary','email','city','province'];
        $errors = [];
        foreach($requiredFields as $field){
            if(empty(updateValues[$field])|| !Validation::string($updateValues[$field])){
                $errors[$field] = ucfirst($field).'为必须项！';
            }
        }
        if(!empty($errors)){
            loadView('listings/edit',[
                'listing'=>$listing,
                'errors'=>$errors
            ]);
            exit;
        }else{
            $updateValues=[];
            foreach(array_keys($updateValues) as $field){
               $updateFields[]="{$field} = :{$field}";
            }
            $updateFields=implode(',',$updateFields);
            $updateQuery="UPDATE listing SET $updateFields WHERE id=:id";
            $updateValues['id'] = $id;
            $this->db->query($updateQuery,$updateValues);
            Session::setFlashMessage('success_message',
'职位信息已更新!');
            redirect('/listings/'.$id)
        }
    }
    /**
     * @return void
     */
    public function search()
    {
        $keywords = isset($_GET['keywords']) ? trim($_GET['keywords']) : '';
        $location = isset($ GET['location']) ? trim($_GET['location']) : '';
        $query ="SELECT * FROM listing WHERE(title LIKE :keywords oR description LIKE :keywords ORtags LIKE :keywords OR company LIKE :keywords) AND(city LIKE :location oR province LIKE :location)";
        $params =[
            'keywords'=>"%{$keywords}%",
            'location'=>"%{$location}%"
        ];
        $listings = $this->db->query($query,$params)->fetchAll();
        loadView('/listings/index',[
            'listings'=> $listings,'keywords'=>$keywords,
            'location'=> $location
        ]);
    }
}